<template>
  <a-spin :spinning="spinning" tip="素材同步中，请耐心等待...">
  <a-card :bordered="false">
    <h3 style="margin-bottom: 20px;">同步至微商城</h3>
    <h4 class="title">买家秀内容</h4>
    <a-form-model
      ref="rulesForm"
      :model="form"
      :rules="rules"
      :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 16 }, sm: { span: 17 } }"
    >
      <a-form-model-item label="内容文案" prop="content">
        <a-textarea
          v-model="form.content"
          :rows="4"
          :maxLength="200"
        />
        <div>内容文案最多输入200字</div>
      </a-form-model-item>
      <a-form-model-item label="图片">
        <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="10" :number="8" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
        <a @click="handleOpenImgList">选择其他搭配图</a>
        <div>*一套 LOOK会关联很多图片，系统默认取出最新的8张图可选，可以自行上传也可以选用LOOK关联的更多搭配图</div>
      </a-form-model-item>
      <a-form-model-item label="视频">
        <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="20" :number="1" :accept="'video/*'" @fileChange="fileVideoChange" v-model="videoList"></JImageUpload>
        <div>视频大小限制20M以下</div>
      </a-form-model-item>
      <a-form-model-item label="关联商品" required>
        <a-table bordered :pagination="false" :columns="productColumns" :data-source="productList" :rowKey="(record, index) => index">
         <span class="product" slot="product" slot-scope="text, record, index">
           <img class="img"  :src="JSON.parse(record.extendJson || '{}').productImage || ''" alt="">
            <div class="product-name">{{JSON.parse(record.extendJson || '{}').productName || ''}}</div>
         </span>
          <span slot="action" slot-scope="text, record, index">
             <a-popconfirm  @confirm="handleRemoveProduct(index)">
               <template slot="title">
                  <p>确定移除该商品吗？</p>
                  <p>移除后，将不会同步该商品至买家秀</p>
                </template>
               <a>移除</a>
             </a-popconfirm>
          </span>
        </a-table>
      </a-form-model-item>
      <h4 class="title">同步设置 <span>设置素材同步至微商城买家秀归属分组/置顶等属性</span></h4>
      <a-form-model-item label="同步至" >
        {{brand.name}}微商城
      </a-form-model-item>
      <a-form-model-item label="归属分组(多选)" prop="buyerShowGroups">
        <template v-for="t in tags">
          <a-checkable-tag
            :key="t.id"
            :checked="form.buyerShowGroups.indexOf(t.id) > -1"
            @change="checked => handleTagChange(t.id, checked)"
          >
            {{ t.name }}
          </a-checkable-tag>
        </template>
      </a-form-model-item>
<!--      <a-form-model-item label="是否置顶展示" prop="isTop">-->
<!--        <a-radio-group v-model="form.isTop">-->
<!--          <a-radio :value="0">否</a-radio>-->
<!--          <a-radio :value="1">是</a-radio>-->
<!--        </a-radio-group>-->
<!--      </a-form-model-item>-->
      <a-form-model-item label="是否在买家秀展示" prop="approvalStatus">
        <a-radio-group v-model="form.approvalStatus">
          <a-radio :value="4">隐藏</a-radio>
          <a-radio :value="5">展示</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button style="margin-right: 8px" @click="handleBack">返回</a-button>
        <a-popconfirm
          title="确定同步素材至微商城买家秀吗？"
          ok-text="确定"
          cancel-text="暂不"
          @confirm="handleSubmit"
        >
          <a-button htmlType="submit" type="primary" >确认同步</a-button>
        </a-popconfirm>
        <div style="color: red;" v-if="state == 1">
          * 该素材已同步至单品搭配，如果继续同步可能会在单品详情页内买家秀和单品搭配区域中重复出现
        </div>
      </a-form-model-item>
    </a-form-model>
    <ImgList :imgList.sync="galleryImgList" :checkedImgList.sync="form.imgList" :visible.sync="imgVisible" @ok="checkedImgChange" ref="imgList"></ImgList>
  </a-card>
  </a-spin>
</template>
<script>
  import JImageUpload from '../../components/JImageUpload'
  import ImgList from '../../components/ImgList'
  import { materialBuyerShowCreate, materialLookDetails, materialBuyerShowGroup, polling } from '@api/micromall/materialTools'
  const productColumns = [
    {
      title: '序号',
      width: '1',
      align: 'center',
      customRender: (text,record,index) => `${index+1}`
    },
    {
      title: '商品',
      width: '10',
      align: 'center',
      scopedSlots: { customRender: 'product' }
    },
    {
      title: '款号',
      width: '4',
      align: 'center',
      dataIndex: 'productCode'
    },
    {
      title: '年份',
      width: '3',
      align: 'center',
      dataIndex: 'year'
    },
    {
      title: '波段',
      width: '3',
      align: 'center',
      dataIndex: 'band'
    },
    {
      title: '季节',
      width: '3',
      align: 'center',
      dataIndex: 'season'
    },
    {
      title: '操作',
      width: '2',
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    components: {
      JImageUpload,
      ImgList
    },
    data() {
      return {
        timer: null,
        state: this.$route.query.state,
        spinning: false,
        imgVisible: false,
        form: {
          content: '',
          imgList: [],
          videoList: [],
          buyerShowGroups: [],
          isTop: 0,
          approvalStatus: 5
        },
        look: {},
        imgList: [],
        galleryImgList: [],
        videoList: [],
        galleryList: [],
        brandList: [
          {
            name: 'JNBY',
            weid: '2738574294',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/c00fdcf9cfe4d96c76561c985d665cb1.png'
          },
          {
            name: 'LESS',
            weid: '2822095692',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/7230584fe1785176a603c38cf89e06a6.png'
          },
          {
            name: '速写',
            weid: '2504948039',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/0ba3ed30cbab042e106d0efa743c388d.png'
          },
          {
            name: 'jnbybyJNBY',
            weid: '4',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/2f628a62770f5ef8098cb25ed4338981.png'
          },
          {
            name: '奥莱',
            weid: '11',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/11f1cff8b6d74eb0429b13d7feb5a7a4.png'
          },
          {
            name: '江南布衣+',
            weid: '5',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/257b88207e65099285664a33514768a4.png'
          },
          {
            name: '蓬马',
            weid: '6924108367',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/36445c65f251d04b5a06b093dc851136.png'
          },
          {
            name: 'APN',
            weid: '15',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/242b088ce360462806641d7a13dc1424.png'
          },
          {
            name: 'JNBYHOME',
            weid: '8348044436',
            logo: 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220311/be2c54b801e746a079a79cff2905ad7a.png'
          }
        ],
        productList: [],
        tags: [],
        productColumns,
        rules: {
          content: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          isTop: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          approvalStatus: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          buyerShowGroups: [{ required: true, message: '请选择', trigger: 'change' }],
        }
      }
    },
    created() {
      this.getDetails()
      this.getMaterialBuyerShowGroup()
    },
    computed: {
      brand() {
        return this.brandList.filter(e => e.weid == this.$route.params.id)[0] || {name: '', logo: ''}
      }
    },
    mounted() {
    },
    beforeDestroy() {
      clearInterval(this.timer)
    },
    methods: {
      // 归属分组(多选)
      getMaterialBuyerShowGroup() {
        const data = {
          brandId: this.$route.params.id
        }
        materialBuyerShowGroup(data).then(res => {
          if (res.code === 200) {
              this.tags = res.data
          } else {
            this.$message.error(res.data.msg)
          }
        })
      },

      // 获取详情
      getDetails() {
        const id = this.$route.params.id
        const lookId = this.$route.query.lookId
        const data = {
          brandId: id,
          lookId
        }
        materialLookDetails(data).then(res => {
          if (res.code === 200) {
            const {look, galleryList, productList} = res.data
            this.form.content = look.briefIntroduction
            this.look = look
            this.galleryList = galleryList
            this.galleryImgList = galleryList.filter(e => e.type === 0).map((i,index) => {
              return{...i, isChecked: false}
            })
            this.imgList = galleryList.filter(e => e.type === 0).map(e => e.url).slice(0, 8)
            this.videoList = galleryList.filter(e => e.type === 1).map(e => e.url)
            this.productList = productList
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
        })
      },

      // 选择搭配图
      checkedImgChange(v) {
        this.imgList= this.form.imgList.concat(v).map(e => e.url)
      },

      //选择其他搭配图
      handleOpenImgList() {
        this.imgVisible=true
      },

      // 归属分组
      handleTagChange(tag, checked) {
        const { buyerShowGroups } = this.form;
        const nextSelectedTags = checked
          ? [...buyerShowGroups, tag]
          : buyerShowGroups.filter(t => t !== tag);
        this.form.buyerShowGroups = nextSelectedTags;
      },

      // 移除关联商品
      handleRemoveProduct(index) {
        this.productList.splice(index, 1)
      },

      getUploadParams() {
        return {
            actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
            headers: {
              authorization: 'authorization-text'
            },
            uploadHost: 'https://img.bzhz.jnbygroup.com/'
          }
      },
      // 图片change
      fileImageChange(list) {
        this.form.imgList = list
      },

      //视频change
      fileVideoChange(list) {
        this.form.videoList = list
      },

      // 确认同步
      handleSubmit() {
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            if (!this.productList.length) {
              this.$message.error('无关联商品！')
              return
            }
            const {imgList, videoList, content, isTop, buyerShowGroups, approvalStatus} = this.form
            const newImgList = imgList.map(e => {
              let filterGalleryList = this.galleryList.filter(i => i.url == e.url)
              if (filterGalleryList.length) {
                return filterGalleryList[0]
              } else {
                return {
                  url: e.url,
                  type: 0
                }
              }
            })

            const newVideoList = videoList.map(e => {
              let filterGalleryList = this.galleryList.filter(i => i.url == e.url)
              if (filterGalleryList.length) {
                return filterGalleryList[0]
              } else {
                return {
                  url: e.url,
                  type: 1
                }
              }
            })
            const {id, publisherName, publisherImg, type, sonType} = this.look
            const data = {
              lookId: id,
              content,
              publisherName: this.brand.name,
              publisherImg: this.brand.logo,
              isTop,
              approvalStatus,
              type,
              sonType,
              productNos: this.productList.map(e => e.productCode),
              buyerShowGroups,
              galleryList: [...newImgList, ...newVideoList]
            }
            this.spinning = true
            materialBuyerShowCreate(data, this.$route.params.id).then(res => {
              if (res.code === 200) {
                this.polling(res.data)
              } else {
                this.spinning = false
                this.$message.error(res.data.msg)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      //素材同步轮训结果
      polling(key) {
        clearInterval(this.timer)
        this.timer = setInterval(() => {
          console.log('timer')
          const data = {
            key: `${key}:${this.look.id}`
          }
          polling(data).then(res => {
            if (res.code === 200) {
              if (res.data == 'success'){
                clearInterval(this.timer)
                this.spinning = false
                this.handleBack()
              } else {
                if (res.data != 'wait') {
                  clearInterval(this.timer)
                  this.spinning = false
                  this.$message.error(res.data)
                }
              }
            } else {
              clearInterval(this.timer)
              this.spinning = false
              this.$message.error(res.data.msg)
            }
          }).catch(err => {
            this.spinning = false
            clearInterval(this.timer)
          })
        }, 1000)
      },

      //返回
      handleBack() {
        this.$router.go(-1)
      },
    }
  }
</script>
<style lang="less" scoped>
  .ant-spin-nested-loading /deep/ .ant-spin{
    top: 50%;
    transform: translateY(-50%);
  }
  /deep/.ant-tag{
    cursor: pointer;
  }
  .title{
    font-size: 15px;
    span{
      color: #999;
      font-size: 14px;
      font-weight: normal;
    }
  }
  .img {
    display: block;
    margin: 0 2px;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
    cursor: pointer;
  }

  .remarks {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
  .product {
    display: flex;
    overflow: hidden;
    align-items: center;
    .img{
      margin: 0;
    }
    .product-name{
      flex: 1;
      margin-left: 5px;
      width: 80px;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
  /deep/ .ant-tag-checkable{
    border-color: #ddd;
  }
</style>
